/**
 * Copyright (C) 2010 Alfredo Morresi
 * 
 * This file is part of RainbowLibs project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package it.rainbowbreeze.libs.data;

import it.rainbowbreeze.libs.common.RainbowLogFacility;
import it.rainbowbreeze.libs.helper.RainbowStreamHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import static it.rainbowbreeze.libs.common.RainbowContractHelper.*;

public class RainbowWebserviceClient implements IRainbowWebserviceClient
{
	//---------- Private fields
    protected static final String LOG_HASH = "RainbowWebserviceClient";
	//indicate that a conversation is in progress
	protected boolean mIsConversationInProgress = false;
	//client used during a conversation
	protected DefaultHttpClient mHttpClient;

	protected final RainbowLogFacility mBaseLogFacility;
	
	
	
    //---------- Constructors
    public RainbowWebserviceClient( RainbowLogFacility logFacility) {
        mBaseLogFacility = checkNotNull(logFacility, "RainbowLogFacility");
    }




	//---------- Public properties



	



	
	//---------- Public class
	public class ServerResponse {
		private final int mResponseCode;
		private final String mResponseMessage;
		private final String mMessageBody;
		
		public int getResponseCode() { return mResponseCode; }
		public String getResponseMessage() { return mResponseMessage; }
		public String getMessageBody() { return mMessageBody; }
		
		private ServerResponse(int responseCode, String responseMessage) {
			mResponseCode = responseCode;
		    mResponseMessage = responseMessage;
            mMessageBody = null;
        }

        private ServerResponse(int responseCode, String responseMessage, String messageBody) {
            mResponseCode = responseCode;
            mResponseMessage = responseMessage;
            mMessageBody = messageBody;
        }
    }



    
    //---------- Public methods

    /* (non-Javadoc)
     * @see it.rainbowbreeze.libs.data.IRainbowWebserviceClient#requestGet(java.lang.String)
     */
    public String requestGet(String url)
        throws ClientProtocolException, IOException
    {
        // reference here:
        // http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/

        HttpGet httpGet;
        String result;

        result = "";

        // prepare a request object
        httpGet = new HttpGet(url);

        // Get hold of the response entity
        result = executeResponse(httpGet);

        return result;
    }


    /* (non-Javadoc)
     * @see it.rainbowbreeze.libs.data.IRainbowWebserviceClient#requestPost(java.lang.String, java.util.HashMap, java.util.HashMap)
     */
    public String requestPost(
            String url,
            HashMap<String, String> headers,
            HashMap<String, String> parameters
        )
        throws ClientProtocolException, IOException, IllegalArgumentException
    {
        // reference here:
        // http://www.androidsnippets.org/snippets/36/
        // another reference, but with different method, here
        // http://www.anddev.org/doing_http_post_with_android-t492.html

        //prepare the post client
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        //create new list of values to pass as post data
        if (headers != null) {
            Iterator<String> it = headers.keySet().iterator();
            String k, v;
            while (it.hasNext()) {
                k = it.next();
                v = headers.get(k);
                httpPost.setHeader(k, v);
            }
        }

        //create new list of values to pass as post data
        if (parameters != null) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            Iterator<String> it = parameters.keySet().iterator();
            String k, v;
            while (it.hasNext()) {
                k = it.next();
                v = parameters.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }

        //execute the request
        String result;

        // Execute HTTP Post Request
        result = executeResponse(httpPost);

        return result;
        
        //update=2 login ok!
    }

    

    /* (non-Javadoc)
     * @see it.rainbowbreeze.libs.data.IRainbowWebserviceClient#startConversation()
     */
    public void startConversation() {
        mIsConversationInProgress = true;
        mHttpClient = new DefaultHttpClient();
    }

    /* (non-Javadoc)
     * @see it.rainbowbreeze.libs.data.IRainbowWebserviceClient#endConversation()
     */
    public void endConversation() {
        mIsConversationInProgress = false;
        mHttpClient = null;
    }





    //---------- Private methods

    /**
     * Execute the GET or POST request
     * 
     */
    protected String executeResponse(HttpUriRequest httpRequest)
        throws ClientProtocolException, IOException
    {
        HttpClient httpClient;
        HttpResponse response;
        String result;

        if (mIsConversationInProgress) {
            httpClient = mHttpClient;
        } else {
            // create the client
            httpClient = new DefaultHttpClient();
        }

        result = "";
    
        response = httpClient.execute(httpRequest);
        // Log.i("XXXX",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        //TODO
        // If the response does not enclose an entity, there is no need
        // to worry about connection release
        if (entity != null) {
            InputStream instream = entity.getContent();
            result = RainbowStreamHelper.convertStreamToString(instream);
        }

        
//        return new ResultOperation<ServerResponse>(
//                new ServerResponse(serverResponseCode, serverResponseMessage));
        return result;
    }

}
